var animation; // 动画实体
var ani_index = 0; // 动画执行次数index（当前执行了多少次）
var aniIntervalId = -1; // 动画定时任务id，通过setInterval来达到无限缩放，记录id，用于结束定时任务
var order = ['red', 'yellow', 'blue', 'green', 'red']
Page({
  data: {
    attachLayer: false,
    savePic: false,
    filePath: "",
    // is_true: 1,
    widthProgress: 0,
    testLoadingLayer: true,
    button: false,
    click_top: {},
    moveType: "",
    top_left: 33,
    top_bottom: 30,
    show: true,
    canMove: true,
    ani_top: '',
    list: [
      'https://fcdn.qiushilaile.com/adx/app-58421611743191519.png',
      'https://fcdn.qiushilaile.com/adx/app-9861611743202110.png',
      'https://fcdn.qiushilaile.com/adx/app-46971611743213109.png',
      'https://fcdn.qiushilaile.com/adx/app-66921611743226736.png',
      'https://fcdn.qiushilaile.com/adx/app-27381611743238884.png',
      'https://fcdn.qiushilaile.com/adx/app-35191611743248060.png',
      'https://fcdn.qiushilaile.com/adx/app-67841611743258108.png',
      'https://fcdn.qiushilaile.com/adx/app-93371611743266810.png'
    ],
    scrollWidth: 0,
    scrollLeftWidth: 0,
    windowWidth: 0,
    fiveBlessingsList: [
      {
        id: 0,
        imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-5301612266491348.png",
      },
      {
        id: 1,
        imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-21471612266510327.png",
      },
      {
        id: 2,
        imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-6391612266530718.png",
      },
      {
        id: 3,
        imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-33501612266543141.png",
      },
      {
        id: 4,
        imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-3571612266558728.png",
      },
      {
        id: 5,
        imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-231612266576042.png",
      },
      {
        id: 6,
        imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-70191612266603598.png"
      },
      {
        id: 7,
        imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-34611612266616895.png"
      },
      // {
      //   imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-72681611641999634.png"
      // },
      // {
      //   imgUrl: "https://fcdn.qiushilaile.com/adx/qualificationMaterials-10721611641971816.png"
      // },
    ],
    collectFiveBlessingsLayer: false,
    familyLuckInfo: true,
    blessingResult: false,
    blessingImgUrl: '',
    blessingName: "",
    clickIndex: 0,
    hasCollectFiveBlessing: [],
    appearStatus: "hidden",
  },
  onLoad: function (options) {
    var hasCollectFiveBlessing = tt.getStorageSync("hasCollectFiveBlessing")
    console.log(hasCollectFiveBlessing)
    var systemInfo = wx.getSystemInfoSync();
    console.log("systemInfo的值是:", systemInfo)
    this.setData({
      screenWidth: systemInfo.windowWidth,
      screenHeight: systemInfo.windowHeight
    })
    console.log(this.data.screenHeight, this.data.screenWidth)
    this.getScrollWidth();
    tt.getImageInfo({
      src: 'https://fcdn.qiushilaile.com/adx/app-79251611715535148.png',
      success: (res) => {
        this.setData({
          shareImgSrc: res.path,
          shareWidth: res.width,
          shareHeight: res.height,
        });
      }
    })
  },
  backClick(){
    tt.redirectTo({
      url: '/pages/pasteBlessings/pasteBlessings'
    });
  },
  getTempFilePath: function () {
    let that = this
    console.log('111')
    tt.canvasToTempFilePath({
      canvasId: 'share',
      success: (res) => {
        console.log(res)
        that.setData({
          shareTempFilePath: res.tempFilePath
        })
        tt.saveImageToPhotosAlbum({
          filePath: that.data.shareTempFilePath,
          success: (res) => {
            console.log(res)
            tt.showToast({ title: "成功保存到本地相册" });
          },
          fail: (err) => {
            console.log(err)
          }
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  //保存至相册
  save() {
    let _this = this
    // if (_this.data.is_true != 1) {
    //   console.log(this.data.is_true)
    //   tt.showModal({
    //     title: '温馨提示',
    //     content: '点击确定前往观看视频',
    //     cancelText: '取消',
    //     success(res) {
    //       if (res.confirm) {
    //         console.log('用户点击确定');
    //         tuiwa.playAd();
    //       } else if (res.cancel) {
    //         console.log('用户点击取消');
    //       }
    //     }
    //   });
    // } else {
    //绘制
    // let that = this;
    // let shareWidth = this.data.shareWidth
    // let shareHeight = this.data.shareHeight
    // let shareImgSrc = this.data.shareImgSrc
    // let context = tt.createCanvasContext('share')
    // // 图片
    // context.drawImage(shareImgSrc, 0, 0, shareWidth, shareHeight)
    // // 生成
    // context.draw(true, this.getTempFilePath)
    // console.log(context)
    let that = this
    let index = this.data.clickIndex
    if (index == 0) {
      this.setData({
        filePath: this.data.list[0]
      })
    } else if (index == 1) {
      this.setData({
        filePath: this.data.list[1]
      })
    } else if (index == 2) {
      this.setData({
        filePath: this.data.list[2]
      })
    } else if (index == 3) {
      this.setData({
        filePath: this.data.list[3]
      })
    } else if (index == 4) {
      this.setData({
        filePath: this.data.list[4]
      })
    } else if (index == 5) {
      this.setData({
        filePath: this.data.list[5]
      })
    } else if (index == 6) {
      this.setData({
        filePath: this.data.list[6]
      })
    } else if (index == 7) {
      this.setData({
        filePath: this.data.list[7]
      })
    }
    console.log(this.data.filePath)
    tt.downloadFile({
      url: this.data.filePath,
      header: {
        "content-type": "application/json",
      },
      success: (res) => {
        console.log(res)

        let filePath = res.tempFilePath;
        tt.saveImageToPhotosAlbum({
          filePath,
          success: (res) => {
            tt.showToast({
              title: "已保存",
              success: (res) => {
               setTimeout(()=>{
                tt.redirectTo({
                  url: '/pages/pasteBlessings/pasteBlessings' 
                });
               },1000)
              }
            });
          },
          fail: (err) => {
            let errType = err.errMsg.includes("saveImageToPhotosAlbum:fail cancel")
              ? "取消保存"
              : "保存失败";
            tt.showModal({
              title: errType,
              content: err.errMsg,
              showCancel: false,
            });
          },
        });
      },
      fail: (err) => {
        tt.showModal({
          title: "下载出错",
          content: err.errMsg,
          showCancel: false,
        });
      },
    });
  },
  save1() {
    let index = this.data.clickIndex
    if (index == 0) {
      this.setData({
        filePath: this.data.list[0]
      })
    } else if (index == 1) {
      this.setData({
        filePath: this.data.list[1]
      })
    } else if (index == 2) {
      this.setData({
        filePath: this.data.list[2]
      })
    } else if (index == 3) {
      this.setData({
        filePath: this.data.list[3]
      })
    } else if (index == 4) {
      this.setData({
        filePath: this.data.list[4]
      })
    } else if (index == 5) {
      this.setData({
        filePath: this.data.list[5]
      })
    } else if (index == 6) {
      this.setData({
        filePath: this.data.list[6]
      })
    } else if (index == 7) {
      this.setData({
        filePath: this.data.list[7]
      })
    }
    console.log(this.data.filePath)

  },
  getScrollWidth() {
    var scrollWidth = wx.getSystemInfoSync().windowWidth;
    this.setData({
      scrollWidth: scrollWidth / 3 * this.data.fiveBlessingsList.length,
      windowWidth: scrollWidth
    })
  },
  scrollleft(e) {
  },
  lowerRight(e) {
  },
  moveStart: function (ent) {
    let index = ent.currentTarget.dataset.index;
    this.setData({
      clickIndex: index,
      appearStatus: true
    })
    this.data.screenWidth;
    this.data.screenHeight;
    this.setData({
      moveType: ent.currentTarget.dataset.type,
    })
    var startY = ent.changedTouches[0].pageY;
    var startX = ent.changedTouches[0].pageX;
    this.setData({
      startX: startX,
      startY: startY,
    })
    console.log(this.data.startX, this.data.startY, this.data.moveType)
  },
  endOfTouch: function (e) {
    console.log(this.data.filePath)
    console.log("width，height", this.data.click_left, this.data.click_top)
    console.log("width，height的值是：", this.data.click_left / this.data.screenWidth, this.data.click_top / this.data.screenHeight)
    if (this.data.screenHeight > 667 && this.data.screenHeight <= 1200) {
      if (this.data.click_left / this.data.screenWidth < 0.39
        && this.data.click_left / this.data.screenWidth > 0.26
        && this.data.click_top / this.data.screenHeight > -0.46
        && this.data.click_top / this.data.screenHeight < -0.37
      ) {
        setTimeout(() => {
          this.setData({
            attachLayer: true
          })
          this.save1()
        }, 500)
        setTimeout(() => {
          this.setData({
            savePic: true
          })
        },1200)
        this.setData({
          show: false,
          canMove: false,
          button: true,
          appearStatus: true,
          attachLayer: true
        })
      }
    } else if (this.data.screenHeight <= 667) {
      if (this.data.click_left / this.data.screenWidth < 0.38
        && this.data.click_left / this.data.screenWidth > 0.26
        && this.data.click_top / this.data.screenHeight > -0.55
        && this.data.click_top / this.data.screenHeight < -0.43
      ) {
        setTimeout(() => {
          this.setData({
            attachLayer: true
          })
          this.save1()
        }, 500)
        setTimeout(() => {
          this.setData({
            savePic: true
          })
        },1000)
        this.setData({
          show: false,
          canMove: false,
          button: true,
          appearStatus: true
        })
      }
    }

  },
  slide: function (ent) {
    if (this.data.canMove == false) {
      this.setData({
        show: false,
        canMove: false,
        button: true
      })
      return;
    }
    var processY = ent.changedTouches[0].pageY;
    var processX = ent.changedTouches[0].pageX;
    let changeX = processX - this.data.startX;
    let changeY = processY - this.data.startY;
    this.setData({
      // click_left: processX - 50, 
      // click_top: processY - 50,
      click_left: ent.touches[0].clientX - 100,
      // click_top: ent.touches[0].clientY - 550,
      click_top: ent.touches[0].clientY - (600-100*(812-this.data.screenHeight)/244.0),
      appearStatus: true
    })
  },
  again() {
    var hasCollectFiveBlessing = this.data.hasCollectFiveBlessing
    tt.redirectTo({
      url: `/pages/pasteBlessings/pasteBlessings?hasCollectFiveBlessing=${hasCollectFiveBlessing}`
    });
  },
  animationFinished(e) {
    this.setData({
      swiperIndex: e.detail.current
    })
  },
  aniScale: function (n) { // 
    if (n % 2 == 0) {
      animation.scale(1.15).step();
    } else {
      animation.scale(1.0).step();
    }
    this.setData({
      animation: animation.export()
    });
  },
  startAnimationInterval: function () { // 开始缩放
    var that = this;
    that.aniScale(++ani_index); // 进行一次缩放
    aniIntervalId = setInterval(function () {
      that.aniScale(++ani_index);
    }, 800); // 每间隔0.8s进行一次缩放
  },
  back() {
    tt.navigateBack({
      delta: 1
    })
  },
  onReady: function () {
    let that = this
    ani_index = 0;
    aniIntervalId = -1;
    this.data.animation = '';
    animation = tt.createAnimation({
      duration: 800,
      timingFunction: 'linear', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
      delay: 0, // 0延迟
      transformOrigin: '50% 50% 0'
    })
    this.startAnimationInterval()
    let hasCollectFiveBlessing = tt.getStorageSync('hasCollectFiveBlessing');
    this.setData({
      fiveBlessingsList: hasCollectFiveBlessing
    })
  },
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function (options) {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})